"""预设BOM差异表"""
from odoo import fields, models, api, _
from odoo.exceptions import UserError


class PresetsBomDiff(models.Model):
    _name = 'sb.presets.bom.diff'
    _inherit = ['portal.mixin', 'mail.thread.main.attachment', 'mail.activity.mixin']
    _order = 'id desc'
    _description = '预设BOM差异表'

    name = fields.Char(string="Name", default="New")

    state = fields.Selection(
        [('draft', 'Draft'), ('confirmed', 'Confirmed'), ('generate', 'Generate'), ('done', 'Done')],
        string="状态", default='draft')
    line_ids = fields.One2many('sb.presets.bom.diff.line', 'diff_id', string="差异行")
    jmi_line_ids = fields.One2many('sb.presets.bom.jmi.line', 'diff_id', string="预设BOM行")

    presets_bom_id = fields.Many2one('sb.presets.bom', string="预设BOM")

    presets_line_ids = fields.One2many('sb.presets.bom.line', related='presets_bom_id.bom_line_ids', string="预设BOM行")
    product_id = fields.Many2one('product.product', string="NPM", related="presets_bom_id.product_id", store=True)

    sheet_type = fields.Selection([('sheet', 'sheet'), ('sheetA', 'sheetA'), ('sheetB', 'sheetB')], string="拼版",
                                  related='presets_bom_id.sheet_type', store=True)

    pnl_width = fields.Float('PNL 经向', related='presets_bom_id.pnl_width', store=True)
    pnl_length = fields.Float('PNL 纬向', related='presets_bom_id.pnl_length', store=True)
    pnl = fields.Float('PCS/PNL', related='presets_bom_id.pnl', store=True)
    set_pnl = fields.Float('SET/PNL', related='presets_bom_id.set_pnl', store=True)

    pcs_set = fields.Float('PCS/SET', related='presets_bom_id.pcs_set', store=True)
    thickness = fields.Float('铜厚', related='presets_bom_id.thickness', store=True)

    # 差异数据
    pnl_width_diff = fields.Float('PNL 经向', readonly=True)
    pnl_length_diff = fields.Float('PNL 纬向', readonly=True)
    pnl_diff = fields.Float('PNL', readonly=True)
    set_pnl_diff = fields.Float('SET/PNL', readonly=True)

    pcs_set_diff = fields.Float('PCS/SET', readonly=True)
    requisition_ids = fields.Many2many('purchase.requisition', string="请购单", compute='_compute_requisition_ids')

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if vals.get("name", _("New")) == _("New"):
                vals["name"] = self.env["ir.sequence"].next_by_code("sb.presets.bom.diff")
        return super().create(vals_list)

    @api.depends('presets_bom_id')
    def _compute_requisition_ids(self):
        for record in self:
            record.requisition_ids = self.env['purchase.requisition'].search([('presets_bom_diff_id', '=', record.id)]).ids

    def action_requisition_ids(self):
        action = self.env["ir.actions.act_window"]._for_xml_id(
            'sb_workflow_purchase.purchase_requisition_approve_action')
        action['domain'] = [('id', 'in', self.requisition_ids.ids)]
        return action

    def confirmed(self):
        """
        确定差异可行, 按钮执行完成后可点击下单请购
        """
        # 查询请购单, 是否存在请购, 入存在则弹框提示, 不存在则确定
        # pr_list = []
        # for rec in self.line_ids:
        #     domain = [('product_id', '=', rec.product_id.product_tmpl_id.id),
        #               ('requisition_id.state', 'in', ['draft', 'wait_approval', 'approved'])]
        #     pr_ids = self.env['purchase.requisition.line'].search(domain)
        #     if pr_ids:
        #         pr_list.extend(pr_ids.requisition_id.ids)
        # if pr_list:  # 已存在商品请购单
        #     res = self.env['sb.presets.bom.wizard'].sudo().create({
        #         'diff_requisition_id': self.id,
        #         'requisition_ids': [(6, 0, pr_list)]
        #     })
        #     return {
        #         'name': _('Confirm Diff'),
        #         'type': 'ir.actions.act_window',
        #         'res_model': 'sb.presets.bom.wizard',
        #         'view_mode': 'form',
        #         'res_id': res.id,
        #         'target': 'new'
        #     }
        # else:
        self.write({'state': 'confirmed'})

    # def create_pr(self):
    #     """生成请购单"""
    #     self.ensure_one()
    #     order_line = self.line_ids.filtered(lambda x: x.product_id.detailed_type == 'product')
    #     if not order_line:
    #         raise UserError(_('There are no products available for preparation'))
    #     action = {
    #         'name': _('material preparation'),
    #         'type': 'ir.actions.act_window',
    #         'view_mode': 'form',
    #         'res_model': 's.sale.order.material.preparation.wizard',
    #         'target': 'new',
    #     }
    #     wizard = self.env['s.sale.order.material.preparation.wizard'].search([('presets_bom_diff_id', '=', self.id)],
    #                                                                          limit=1)
    #
    #     res = wizard.with_context(default_sale_order_line_ids_str=','.join(
    #         [str(i.id) for i in self.mapped('presets_bom_id.sale_order_line_ids')]),
    #         active_model='sb.presets.bom.diff').default_get(
    #         list(wizard.fields_get()))
    #     res_id = wizard.create(res)
    #     res_id.onchange_qty()
    #     action['res_id'] = res_id.id
    #     return action


class PresetsBomDiffLine(models.Model):
    _name = 'sb.presets.bom.diff.line'
    _description = '预设BOM差异表行'

    diff_id = fields.Many2one('sb.presets.bom.diff', string="预设BOM差异表", ondelete='cascade')
    product_id = fields.Many2one('product.product', string="Product")
    default_code = fields.Char(string="Default code", related="product_id.default_code", store=True)
    product_uom_id = fields.Many2one('uom.uom', string="Uom")
    panel_qty = fields.Float(string="PANEL Qty", digits=(10, 6))
    origin_qty = fields.Float(string="Origin PANEL Qty", digits=(10, 6))
    diff_qty = fields.Float(string="Diff", digits=(10, 6), compute='_compute_diff_qty', store=True)
    is_presets = fields.Boolean(string="")
    is_jmi = fields.Boolean(string="")

    @api.depends('origin_qty', 'panel_qty')
    def _compute_diff_qty(self):
        for rec in self:
            rec.diff_qty = abs(rec.origin_qty - rec.panel_qty)


class PresetsBomJmiLine(models.Model):
    _name = 'sb.presets.bom.jmi.line'
    _description = 'Jmi提交明细'

    diff_id = fields.Many2one('sb.presets.bom.diff', string="预设BOM差异表", ondelete='cascade')
    product_id = fields.Many2one('product.product', string="Product")
    default_code = fields.Char(string="Default code", related="product_id.default_code", store=True)
    product_uom_id = fields.Many2one('uom.uom', string="Uom")
    panel_qty = fields.Float(string="PANEL Qty", digits=(10, 6))
